package com.com.gmail.at.vssabinin.adminclient;

import java.util.HashSet;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

import DTO.StationDTO;
import javax.swing.ListSelectionModel;

public class StationManager extends javax.swing.JDialog {

	private static final long serialVersionUID = 1L;

    public StationManager(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }
    
    private HashSet<StationDTO> createdStations = new HashSet<StationDTO>();
    private HashSet<StationDTO> removedStations = new HashSet<StationDTO>();
    
    private boolean changes = false;
  
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        stationList = new javax.swing.JList();
        stationList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        deleteStation = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        addStation = new javax.swing.JButton();
        save = new javax.swing.JButton();
        stationName = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        goBack = new javax.swing.JButton();
        loadAll = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        stationList.setModel(new javax.swing.AbstractListModel() {
            /**
			 * 
			 */
			private static final long serialVersionUID = 1L;
			String[] strings = { "Stations" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(stationList);

        deleteStation.setText("delete");
        deleteStation.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                deleteStationMouseReleased(evt);
            }
        });

        jLabel1.setText("Choose a station and press delete:");

        addStation.setText("add station");
        addStation.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                addStationMouseReleased(evt);
            }
        });

        save.setText("save changes");
        save.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                saveMouseReleased(evt);
            }
        });

        stationName.setText("station name");

        jLabel2.setText("Add a new station:");

        goBack.setText("go back to the main menu");
        goBack.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                goBackMouseReleased(evt);
            }
        });

        loadAll.setText("Refresh the list");
        loadAll.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                loadAllMouseReleased(evt);
            }
        });

        jLabel3.setText("First you add or delete stations. After you press save changes.");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(110, 110, 110)
                                .addComponent(loadAll))
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(stationName, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(addStation, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(jLabel3)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(goBack)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(save))
                            .addComponent(jScrollPane1)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGap(24, 24, 24)
                                .addComponent(deleteStation, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(loadAll)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(deleteStation))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(stationName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(addStation))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(goBack)
                    .addComponent(save))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE)
                .addContainerGap())
        );

        jLabel3.getAccessibleContext().setAccessibleName("First you add or delete stations. After you press save changes, to \nsend datat to the server. Refresh to load stations from server.");

        pack();
    }
    public static StationManager stationInstance = new StationManager(Main.mainInstance, true);
    
    private  DefaultListModel listModel = new DefaultListModel();
    
    private void update() {
    	this.createdStations.clear();
    	this.removedStations.clear();
    	this.changes = false;
    	listModel.clear();
    	Main.mainInstance.client.sendThroughProtocol("adminManageStatDat", "");
        Protocol.Message message = Main.mainInstance.client.readThroughProtocol();
        if (message.getType().equals("ok")) {
        	@SuppressWarnings("unchecked")
        	List<StationDTO> station = (List<StationDTO>)message.getObject();
            for (int i = 0; i < station.size(); i++) {
            	listModel.addElement("Station:  " + station.get(i).getStationName() + 
            		"   id:  " + station.get(i).getStationID());
            }
        } else if (message.getType().equals("no")) {
        	listModel.addElement("No stations in database");
        }
        StationManager.stationInstance.stationList.setModel(listModel);
    }
    
    private void loadAllMouseReleased(java.awt.event.MouseEvent evt) {
    	this.update();
    }

    private void addStationMouseReleased(java.awt.event.MouseEvent evt) {
    	StationDTO station = new StationDTO();
    	station.setStationName(this.stationName.getText());
    	this.createdStations.add(station);
    	this.listModel.addElement("Station:  " + station.getStationName() + 
      			"   id:  ");
    	StationManager.stationInstance.stationList.setModel(listModel);
    	this.changes = true;
    }

    private void saveMouseReleased(java.awt.event.MouseEvent evt) {
        if (!this.createdStations.isEmpty()) {
        	Main.mainInstance.client.sendThroughProtocol("adminCreateNewStations", this.createdStations);
        	Protocol.Message message = Main.mainInstance.client.readThroughProtocol();
        	if (message.getType().equals("ok")) {
        		this.createdStations.clear();	
        	}
        }
        if (!this.removedStations.isEmpty()) {
        	Main.mainInstance.client.sendThroughProtocol("adminRemoveStations", this.removedStations);
        	Protocol.Message message1 = Main.mainInstance.client.readThroughProtocol();
        	if (message1.getType().equals("ok")) {
        		this.removedStations.clear();
        	}
		}
        this.update();
        JOptionPane.showMessageDialog(null, "You have successfully made ​​changes!"); 
    }

    private void deleteStationMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_deleteStationMouseReleased
    	int selection = JOptionPane.showConfirmDialog(null, "This will delete the station, and all the schedules and tickets, that are associated with it!", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
    	if (selection == JOptionPane.YES_OPTION) {
    		String selected = (String) this.stationList.getSelectedValue();
            this.listModel.remove(this.stationList.getSelectedIndex());
            StationManager.stationInstance.stationList.setModel(listModel); 
            String name = selected.replace("Station:  ", "").replaceAll("   id.+", "");
            StationDTO station = new StationDTO();
        	station.setStationName(name);
        	this.removedStations.add(station);
        	this.changes = true;
    	}
    }
    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        this.update();
    }

    private void goBackMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_goBackMouseReleased
    	if (changes) {
    		int selection = JOptionPane.showConfirmDialog(null, "Do you want to save changes?", "Information", 
        			JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE);
        	if (selection == JOptionPane.YES_OPTION) {
        		this.saveMouseReleased(evt);
        	}
    	}
    	Main.mainInstance.loginViewSet();
        this.dispose();
    }

    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(StationManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(StationManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(StationManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(StationManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
       
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                StationManager dialog = new StationManager(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
           }
        });
    }  
    private javax.swing.JButton addStation;
    private javax.swing.JButton deleteStation;
    private javax.swing.JButton goBack;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton loadAll;
    private javax.swing.JButton save;
    private javax.swing.JList stationList;
    private javax.swing.JTextField stationName;
}
